package com.example.softwarearchitectureexamples.controller;

import com.example.softwarearchitectureexamples.dto.User;
import com.example.softwarearchitectureexamples.exception.XException;
import com.example.softwarearchitectureexamples.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

//仅接收和返回数据，不返回视图
@RestController
@Slf4j
@RequestMapping("/api/")
@RequiredArgsConstructor
public class LoginController {
    private final UserService userService;

    //返回json数据，通过键值对返回
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody User user,HttpServletResponse response) {
        User u = userService.getUser(user.getAccount(), user.getPassword());
        if (u == null) {
            throw new XException("账户密码错误");
        }
        // 前端在每次请求时都携带token
        response.addHeader("uid", u.getId().toString());
        response.addHeader("role", u.getRole().toString());
        return  Map.of("user", u);
    }
}
